import {reqCartList, reqDeleteCartBySkuId, reqUpdateCheckedById} from '@/api'
const state={
    getCartList:{}
}
const mutations={
    GETCARTLIST(state,getCartList){
        state.getCartList=getCartList
    }
}
const actions={
    //获取购物车列表数据
    async getCartList({commit}){
        let result = await reqCartList()
        if(result.code==200){
            commit('GETCARTLIST',result.data)
        }
    },
    //删除购物车商品---第一个参数默认为上下文内容 context包含{commit}
    async deleteCartListBySkuId(context,skuId){
        let result = await reqDeleteCartBySkuId(skuId)
        if(result.code==200){
            return'ok'
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    //修改商品状态
    async updateCheckedById(context,{skuId,isChecked}){
      let result = await reqUpdateCheckedById(skuId,isChecked)
      if(result.code==200){
        return 'ok'
      }else{
        return Promise.reject(new Error('faile'))
      }
    },
    //删除选中的全部商品
    deleteAllCart({getters,dispatch}){
        let promiseAll=[]
        getters.getCartList.cartInfoList.forEach(element => {
            let promise=element.isChecked==1?dispatch('deleteCartListBySkuId',element.skuId):''
            promiseAll.push(promise)
        });
        return Promise.all(promiseAll)
    },
    //设置全选按钮
    updateAllisChecked({state,dispatch},isChecked){
        let promiseAll=[]
        state.getCartList[0].cartInfoList.forEach(element => {
            let promise=dispatch('updateCheckedById',{skuId:element.skuId,isChecked})
            promiseAll.push(promise)
        });
        return Promise.all(promiseAll)
    }
}
const getters={
    getCartList(state){
        return state.getCartList[0]||[]
    },
}
export default({
    state,
    mutations,
    actions,
    getters
})